#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
挂机界面
提供挂机相关功能
"""

import os
import time
from ..game.game_manager import GameManager

class IdleUI:
    """
    挂机界面类
    """
    
    def __init__(self, game_manager: GameManager):
        """
        初始化挂机界面
        
        Args:
            game_manager: 游戏管理器
        """
        self.game_manager = game_manager
    
    def clear_screen(self):
        """
        清屏
        """
        os.system('cls' if os.name == 'nt' else 'clear')
    
    def show_header(self):
        """
        显示标题
        """
        print("\n" + "=" * 50)
        print("                挂机系统")
        print("=" * 50)
    
    def show_current_status(self):
        """
        显示当前挂机状态
        """
        current_character = self.game_manager.get_current_character()
        
        if not current_character:
            print("\n请先选择角色!")
            return False
        
        print(f"\n当前角色: {current_character.name} (Lv.{current_character.level} {current_character.character_class})")
        print(f"生命值: {current_character.hp}/{current_character.max_hp}")
        print(f"经验值: {current_character.exp}/{current_character.exp_to_next_level}")
        
        if current_character.is_idle:
            idle_status = self.game_manager.get_idle_status()
            if idle_status:
                duration = idle_status['duration']
                hours = int(duration // 3600)
                minutes = int((duration % 3600) // 60)
                seconds = int(duration % 60)
                
                print(f"\n挂机状态: 进行中")
                print(f"挂机地点: {idle_status['location_name']}")
                print(f"挂机时长: {hours}小时 {minutes}分钟 {seconds}秒")
                
                # 显示当前可获得的奖励
                current_rewards = self.game_manager.update_idle_rewards()
                if current_rewards and current_rewards.get('exp', 0) > 0:
                    print(f"当前可获得经验: {current_rewards['exp']}")
        elif current_character.is_in_battle:
            print(f"\n状态: 战斗中 (无法挂机)")
        else:
            print(f"\n状态: 空闲")
        
        return True
    
    def show_idle_locations(self):
        """
        显示挂机地点
        """
        current_character = self.game_manager.get_current_character()
        locations = self.game_manager.get_available_idle_locations()
        
        if current_character:
            locations = self.game_manager.idle_manager.get_available_locations(current_character)
        
        print("\n可用挂机地点:")
        print("-" * 80)
        print(f"{'序号':<4} {'地点名称':<12} {'描述':<25} {'经验倍率':<8} {'等级要求':<10} {'状态'}")
        print("-" * 80)
        
        for i, location in enumerate(locations, 1):
            level_req = f"{location['min_level']}-{location['max_level']}"
            if location['max_level'] == 999:
                level_req = f"{location['min_level']}+"
            
            status = "可用" if location['available'] else location['reason']
            
            print(f"{i:<4} {location['name']:<12} {location['description']:<25} "
                  f"{location['exp_multiplier']:<8} {level_req:<10} {status}")
        
        print("-" * 80)
        return locations
    
    def start_idle(self):
        """
        开始挂机
        """
        current_character = self.game_manager.get_current_character()
        
        if not current_character:
            print("\n请先选择角色!")
            input("按回车键继续...")
            return
        
        if current_character.is_idle:
            print("\n角色已在挂机中!")
            input("按回车键继续...")
            return
        
        if current_character.is_in_battle:
            print("\n角色正在战斗中，无法挂机!")
            input("按回车键继续...")
            return
        
        self.clear_screen()
        print("\n" + "=" * 40)
        print("           开始挂机")
        print("=" * 40)
        
        locations = self.show_idle_locations()
        available_locations = [loc for loc in locations if loc['available']]
        
        if not available_locations:
            print("\n暂无可用的挂机地点!")
            input("按回车键继续...")
            return
        
        while True:
            try:
                choice = input(f"\n请选择挂机地点 (1-{len(locations)}) 或输入 0 返回: ").strip()
                
                if choice == "0":
                    return
                
                choice_idx = int(choice) - 1
                
                if 0 <= choice_idx < len(locations):
                    location = locations[choice_idx]
                    
                    if not location['available']:
                        print(f"\n无法选择此地点: {location['reason']}")
                        continue
                    
                    # 开始挂机
                    success, message = self.game_manager.start_idle(location['id'])
                    print(f"\n{message}")
                    
                    if success:
                        print(f"\n挂机信息:")
                        print(f"  地点: {location['name']}")
                        print(f"  描述: {location['description']}")
                        print(f"  经验倍率: {location['exp_multiplier']}x")
                        print(f"\n角色将在此地点自动获得经验，你可以随时返回查看进度或停止挂机。")
                    
                    input("\n按回车键继续...")
                    return
                else:
                    print("无效选择，请重新输入!")
            except ValueError:
                print("请输入数字!")
    
    def stop_idle(self):
        """
        停止挂机
        """
        current_character = self.game_manager.get_current_character()
        
        if not current_character:
            print("\n请先选择角色!")
            input("按回车键继续...")
            return
        
        if not current_character.is_idle:
            print("\n角色未在挂机状态!")
            input("按回车键继续...")
            return
        
        self.clear_screen()
        print("\n" + "=" * 40)
        print("           停止挂机")
        print("=" * 40)
        
        # 显示当前挂机状态
        idle_status = self.game_manager.get_idle_status()
        if idle_status:
            duration = idle_status['duration']
            hours = int(duration // 3600)
            minutes = int((duration % 3600) // 60)
            seconds = int(duration % 60)
            
            print(f"\n当前挂机信息:")
            print(f"  地点: {idle_status['location_name']}")
            print(f"  时长: {hours}小时 {minutes}分钟 {seconds}秒")
            
            # 显示预期奖励
            current_rewards = self.game_manager.update_idle_rewards()
            if current_rewards:
                print(f"  预期经验奖励: {current_rewards.get('exp', 0)}")
        
        # 确认停止
        confirm = input("\n确定要停止挂机吗？(y/n): ").strip().lower()
        
        if confirm in ['y', 'yes', '是']:
            old_level = current_character.level
            old_exp = current_character.exp
            
            success, message, rewards = self.game_manager.stop_idle()
            
            print(f"\n{message}")
            
            if success and rewards:
                print(f"\n奖励详情:")
                if rewards.get('exp', 0) > 0:
                    print(f"  获得经验: {rewards['exp']}")
                    print(f"  经验变化: {old_exp} → {current_character.exp}")
                    
                    if current_character.level > old_level:
                        print(f"  等级提升: {old_level} → {current_character.level} (恭喜升级!)")
                
                duration = rewards.get('idle_duration', 0)
                if duration > 0:
                    if duration >= 3600:
                        hours = int(duration // 3600)
                        minutes = int((duration % 3600) // 60)
                        print(f"  挂机时长: {hours}小时 {minutes}分钟")
                    elif duration >= 60:
                        minutes = int(duration // 60)
                        seconds = int(duration % 60)
                        print(f"  挂机时长: {minutes}分钟 {seconds}秒")
                    else:
                        print(f"  挂机时长: {duration:.1f}秒")
        else:
            print("\n已取消停止挂机")
        
        input("\n按回车键继续...")
    
    def show_menu_options(self):
        """
        显示菜单选项
        """
        current_character = self.game_manager.get_current_character()
        
        print("\n请选择操作:")
        
        if current_character and current_character.is_idle:
            print("1. 查看挂机状态")
            print("2. 停止挂机")
        else:
            print("1. 开始挂机")
            print("2. 查看挂机地点")
        
        print("0. 返回主菜单")
        print("-" * 30)
    
    def handle_menu_choice(self, choice: str) -> bool:
        """
        处理菜单选择
        
        Args:
            choice: 用户选择
            
        Returns:
            是否继续显示挂机界面
        """
        current_character = self.game_manager.get_current_character()
        
        if choice == "1":
            if current_character and current_character.is_idle:
                # 查看挂机状态（刷新显示）
                pass
            else:
                self.start_idle()
        elif choice == "2":
            if current_character and current_character.is_idle:
                self.stop_idle()
            else:
                # 查看挂机地点
                self.clear_screen()
                print("\n" + "=" * 40)
                print("           挂机地点")
                print("=" * 40)
                self.show_idle_locations()
                input("\n按回车键继续...")
        elif choice == "0":
            return False
        else:
            print("\n无效选择，请重新输入!")
            input("按回车键继续...")
        
        return True
    
    def show(self):
        """
        显示挂机界面
        """
        running = True
        
        while running:
            self.clear_screen()
            self.show_header()
            
            if not self.show_current_status():
                input("按回车键继续...")
                break
            
            self.show_menu_options()
            
            try:
                choice = input("请输入选择: ").strip()
                running = self.handle_menu_choice(choice)
            except KeyboardInterrupt:
                print("\n\n返回主菜单...")
                break
            except Exception as e:
                print(f"\n发生错误: {e}")
                input("按回车键继续...")